const express = require("express");
const axios = require('axios');

const router = express.Router();
const cache = {};

router.get('/convert', async function(req, res) {
  if (!req.query.from || !req.query.to) {
    return res.sendStatus(400);
  }

  try {
    // Create convert pair
    const q = `${req.query.from}_${req.query.to}`;

    const nowInSec = Math.floor(Date.now()/1000);

    // Check cache first
    const cacheData = cache[q];
    if (cacheData) {
      // If the data was cached within one hour, use it
      if (nowInSec - cacheData.queryTime < 3600) {
        return res.json(cacheData.conv);
      }
    }

    // Cache expired or no cache found
    const conv = await axios.get(`https://free.currencyconverterapi.com/api/v6/convert?q=${q}&compact=ultra&apiKey=05e0e5c71e4de60ef4ab`);

    // Cache the latest query result
    cache[q] = {
      conv: conv.data,
      queryTime: nowInSec
    };

    res.json(conv.data);
  } catch (e) {
    console.error(e);
    return res.status(500).send(e.toString());
  }
});

module.exports = router;
